﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.DirectoryServices;
using System.Threading;

namespace FindAndDeleteAllDeadUsersFromFarm
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        class UserToDelete
        {
            public string Url { get; set; }
            public string Name { get; set; }
            public bool Delete { get; set; }
        }

        List<UserToDelete> _AllDeadUsersFound = new List<UserToDelete>();

        private void FindAllDeadUsersInFarmButton_Click(object sender, RoutedEventArgs e)
        {

            (sender as Button).IsEnabled = false;
            (sender as Button).Content = "Finding all dead users...";

            stackPanel1.Children.Remove(LDAPQueryLabel);
            stackPanel1.Children.Remove(LDAPQueryTextBox);

            ThreadStart threadStart = new ThreadStart(delegate
                {
                    var directorySearcher = new DirectorySearcher(LDAPQueryTextBox.Text);
                    var allADUsers = directorySearcher.FindAll();
                    List<string> adUserNames = new List<string>();
                    foreach (SearchResult searchResult in allADUsers)
                    {
                        adUserNames.Add("NREL_NT\\" + (searchResult.Properties["SAMACCOUNTNAME"] as ResultPropertyValueCollection)[0].ToString());
                    }


                    var webApplications = SPWebService.ContentService.WebApplications;
                    foreach (var webApplication in webApplications)
                    {
                        var sites = webApplication.Sites;
                        foreach (SPSite site in sites)
                        {
                            using (site)
                            {
                                var webs = site.AllWebs;
                                foreach (SPWeb web in webs)
                                {
                                    using (web)
                                    {
                                        var users = web.SiteUsers;
                                        foreach (SPUser user in users)
                                        {
                                            if (!adUserNames.Contains(user.LoginName) && _AllDeadUsersFound.Count < 10)
                                            {
                                                _AllDeadUsersFound.Add(new UserToDelete()
                                                {
                                                    Name = user.LoginName,
                                                    Url = web.Url,
                                                    Delete = true
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
            threadStart.BeginInvoke(FoundAllDeadUsers, null);
        }

        public void FoundAllDeadUsers(IAsyncResult result)
        {
            _AllDeadUsersFound.Sort(delegate(UserToDelete user1, UserToDelete user2)
                {
                    return (user1.Url + user1.Name).CompareTo(user2.Url + user2.Name);
                });

            Dispatcher.Invoke(
          System.Windows.Threading.DispatcherPriority.Normal,
          new Action(
              delegate()
              {
                  foreach (var item in _AllDeadUsersFound)
                  {
                      grid1.RowDefinitions.Add(new RowDefinition());
                      var label = new Label() { Content = item.Url };
                      label.SetValue(Grid.RowProperty, grid1.RowDefinitions.Count - 1);
                      label.SetValue(Grid.ColumnProperty, 0);
                      grid1.Children.Add(label);
                      label = new Label() { Content = item.Name };
                      label.SetValue(Grid.RowProperty, grid1.RowDefinitions.Count - 1);
                      label.SetValue(Grid.ColumnProperty, 1);
                      grid1.Children.Add(label);
                      var checkbox = new CheckBox();
                      checkbox.SetValue(Grid.RowProperty, grid1.RowDefinitions.Count - 1);
                      checkbox.SetValue(Grid.ColumnProperty, 2);
                      Binding binding = new Binding("Delete");
                      binding.Mode = BindingMode.TwoWay;
                      binding.Source = item;
                      checkbox.SetBinding(CheckBox.IsCheckedProperty, binding);
                      grid1.Children.Add(checkbox);
                  }

                  Button deleteAllCheckedUsersButton = new Button();
                  deleteAllCheckedUsersButton.Content = "Remove all selected dead users";
                  deleteAllCheckedUsersButton.Width = 169;
                  stackPanel1.Children.Insert(1, deleteAllCheckedUsersButton);
                  deleteAllCheckedUsersButton.Click += new RoutedEventHandler(deleteAllCheckedUsersButton_Click);

                  stackPanel1.Children.Remove(FindAllDeadUsersInFarmButton);
              }
            ));
        }

        void deleteAllCheckedUsersButton_Click(object sender, RoutedEventArgs e)
        {
            (sender as Button).IsEnabled = false;
            (sender as Button).Content = "Deleting all selected dead users...";

            ThreadStart threadStart = new ThreadStart(delegate
                {
                    var webApplications = SPWebService.ContentService.WebApplications;
                    foreach (var webApplication in webApplications)
                    {
                        var sites = webApplication.Sites;
                        foreach (SPSite site in sites)
                        {
                            using (site)
                            {
                                var webs = site.AllWebs;
                                foreach (SPWeb web in webs)
                                {
                                    using (web)
                                    {
                                        var users = web.SiteUsers;
                                        var deadUsersToDelete = _AllDeadUsersFound.Where(deadUser => deadUser.Url == web.Url && deadUser.Delete);


                                        foreach (var userToDelete in deadUsersToDelete)
                                        {
                                            web.SiteUsers.Remove(userToDelete.Name);
                                        }

                                        web.Update();
                                    }
                                }
                            }
                        }
                    }
                });
            threadStart.BeginInvoke(DoneCreatingUsers, null);
        }

        public void DoneCreatingUsers(IAsyncResult result)
        {
            Dispatcher.Invoke(
            System.Windows.Threading.DispatcherPriority.Normal,
          new Action(
              delegate()
              {
                  MessageBox.Show("Done Deleting Users");
              }
            ));
        }
    }
}
